package org.southyin.securitysamples.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.southyin.securitysamples.commons.CommonsResp;
import org.southyin.securitysamples.mapper.ArticleMapper;
import org.southyin.securitysamples.model.Article;
import org.southyin.securitysamples.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class ArticleService {
    @Autowired
    ArticleMapper articleMapper;
    public PageInfo listArticle(String keyWords, int pageNum, int pageSize,long status) {
        PageHelper.startPage(pageNum, pageSize);
        long adminId = -1;
        List<Article> list = null;
        if (status == 5) {
            // 查询 管理员 自己的文章信息
            adminId = ((User) SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getId();
            list = articleMapper.listArticleOfAdmin(keyWords,adminId);
        }else{
            // 查询 平台用户 文章信息
            list = articleMapper.listArticle(keyWords,status);
        }
        PageInfo<Article> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    public CommonsResp insertArticle(Article article) {
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        article.setAdminId(principal.getId());
        int count = articleMapper.insertArticle(article);
        if (count == 0) {
            return CommonsResp.failed();
        }
        return CommonsResp.succeess(200,"操作成功",article.getId());
    }

    public CommonsResp updateArticle(Article article) {
        int count = articleMapper.updateArticle(article);
        if (count == 0) {
            return CommonsResp.failed();
        }
        return CommonsResp.succeess(200,"操作成功");
    }

    public Article getArticleById(Long id) {
        return articleMapper.getArticleById(id);
    }

    public Article getArticleDetailsById(Long id,Integer status) {
        if (status == 5) {
            return  articleMapper.getArticleDetailsOfAdminById(id);
        }
        return articleMapper.getArticleDetailsOfCustomerById(id);
    }
}
